package mobile.service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.ibatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.aton.db.SessionFactory;
import com.aton.util.CacheUtil;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;

import domain.UserMoneyStats;
import enums.TaskStatus;
import mobile.vo.UserInfo;
import models.BuyerDepositRecord;
import models.BuyerTask;
import models.Notice;
import models.SellerPledgeRecord;
import models.Task;
import models.Notice.Role;
import models.SellerPledgeRecord.PledgeAction;
import models.User;
import models.mappers.BuyerTaskMapper;
import models.mappers.SellerPledgeRecordMapper;
import models.mappers.TaskMapper;
import models.mappers.fund.BuyerDepositRecordMapper;
import net.spy.memcached.protocol.GetCallbackWrapper;
import vos.PersonalInfoVo;
import vos.TaskCountVo;
import vos.TaskSearchVo;

/**
 * 用户服务类
 * 
 * @author zhiyuan
 * @version v1.0
 * @since 2016年12月8日 下午10:17:15
 */
public class UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserService.class);

	/**
	 * 查询用户信息
	 * 
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2016年12月8日
	 * @param imei
	 * @return
	 */
	public static UserInfo getUserInfo(String imei) {

		UserInfo userInfo = new UserInfo();

		Long userId = CacheUtil.get(imei);
		// 查询用户信息

		User cuser = User.findByIdWichCache(userId);

		userInfo.setDeposit(UserService.statisticsCanWithdrawCash(cuser) + UserService.statisticsPadPayment(cuser));
		userInfo.setIngot(cuser.ingot);

		// 任务统计
		Multimap waitingTaskCountInfo = BuyerTask.findWaitingTaskCountInfo(cuser.id);

		List<TaskCountVo> list = (List) waitingTaskCountInfo.get("recieved");
		TaskSearchVo taskSearchVo = TaskSearchVo.newInstance();
		int count = 0;
		count = BuyerTask.countBuyerTaskListForApp(
				taskSearchVo.buyerId(cuser.id).statusIn(TaskStatus.RECIEVED, TaskStatus.WAIT_PAY));
		userInfo.setWaitPay(count);

		count = BuyerTask.countBuyerTaskListForApp(taskSearchVo.buyerId(cuser.id).statusIn(TaskStatus.WAIT_SEND_GOODS,
				TaskStatus.WAIT_EXPRESS_PRINT, TaskStatus.EXPRESS_PRINT, TaskStatus.WAIT_CONFIRM));
		userInfo.setWaitRecevie(count);

		count = BuyerTask.countBuyerTaskListForApp(taskSearchVo.buyerId(cuser.id).statusIn(
				TaskStatus.WAIT_BUYER_CONFIRM_EDITED_SYS_REFUND, TaskStatus.WAIT_SELLER_CONFIRM_SYS_REFUND,
				TaskStatus.WAIT_BUYER_CONFIRM_SYS_REFUND, TaskStatus.WAIT_REFUND));
		userInfo.setWaitRefund(count);

		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BuyerTaskMapper mapper = ss.getMapper(BuyerTaskMapper.class);
			// 涉及“已支付”~“已退款”中的所有状态
			List<TaskStatus> statuses = Lists.newArrayList(TaskStatus.WAIT_SEND_GOODS, TaskStatus.WAIT_EXPRESS_PRINT,
					TaskStatus.EXPRESS_PRINT, TaskStatus.WAIT_CONFIRM, TaskStatus.WAIT_REFUND,
					TaskStatus.WAIT_SELLER_CONFIRM_SYS_REFUND, TaskStatus.WAIT_BUYER_CONFIRM_SYS_REFUND,
					TaskStatus.WAIT_BUYER_CONFIRM_EDITED_SYS_REFUND, TaskStatus.BUYER_REJECT_SYS_REFUND,
					TaskStatus.WAIT_SYS_REFUND);
			PersonalInfoVo vo = mapper.selectBuyerPaidFeeInfo(userId, statuses);

			// 待发放佣金、冻结金币
			// 涉及“已完成”、“已取消”之外的全部状态
			statuses = Lists.newArrayList(TaskStatus.FINISHED, TaskStatus.CANCLED);
			vo = mapper.selectBuyerExcutingInfo(userId, statuses);
			userInfo.setUnreceivedRewardIngot(vo.sumRewardIngot);
			userInfo.setLockedIngot(vo.getLockedIngot());
		} catch (Exception ex) {
			ex.printStackTrace();
			logger.error("查询做单收入时发生错误，{}", ex.getMessage());
		} finally {
			ss.close();
		}

		return userInfo;
	}

	// 计算垫付本金
	public static long statisticsPadPayment(User user) {
		long total = 0;
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			/*
			 * 垫付本金统计
			 */
			BuyerTaskMapper mapper = ss.getMapper(BuyerTaskMapper.class);
			// 统计维度：商家返款、平台返款
			List<TaskStatus> statuses = Lists.newArrayList(TaskStatus.RECIEVED, TaskStatus.WAIT_PAY, TaskStatus.CANCLED,
					TaskStatus.FINISHED);
			List<UserMoneyStats> buyerDepositStats = mapper.sumPaidFeeByBuyerIdAndStatusNotIn(user.id, statuses);

			UserMoneyStats lockedSysRefundDeposit = new UserMoneyStats();
			UserMoneyStats lockedSellerRefundDeposit = new UserMoneyStats();
			for (UserMoneyStats stats : buyerDepositStats) {
				// 平台返款
				if (BooleanUtils.isTrue(stats.sysRefund)) {
					lockedSysRefundDeposit.amount = stats.amount;
					lockedSysRefundDeposit.count = stats.count;
					continue;
				}
				// 商家直接返款
				lockedSellerRefundDeposit.amount = stats.amount;
				lockedSellerRefundDeposit.count = stats.count;
			}
			
			total = lockedSellerRefundDeposit.amount + lockedSysRefundDeposit.amount;
		} finally {
			ss.close();
		}
		return total;
	}
	
	
	/**
	 * 统计可提现本金
	 * @author 刘志远<yuanzhi-2@163.com>
	 * @since 2017年1月21日
	 * @param user
	 * @return
	 */
	public static long statisticsCanWithdrawCash(User user){
		long total = 0;
		SqlSession ss = SessionFactory.getSqlSession();
		try {
			BuyerDepositRecord depositRecord = ss.getMapper(BuyerDepositRecordMapper.class).selectLastRecord(user.id);
			if (depositRecord != null) {
				total = depositRecord.balance;
			}
		} finally {
			ss.close();
		}
		return total;
	}
	
	
}
